/*
 * @lc app=leetcode.cn id=142 lang=cpp
 *
 * [142] 环形链表 II
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if (head == nullptr)
            return head;

        ListNode* slow = head, *fast = head;
        for (; fast != nullptr;) {
            if (fast->next == nullptr || fast->next->next == nullptr)
                return nullptr;

            fast = fast->next->next;
            slow = slow->next;

            //找到交点
            if (fast == slow)
                break;
        }
        
        
        //寻找环起点, 让 slow 从头走起, fast 从交点走起, 相遇后便是起点
        //Floyd 判圈算法
        slow = head;
        for (; slow != fast; slow = slow->next, fast = fast->next);

        return slow;
    }
};
// @lc code=end

